#!/bin/bash

# 定义日志文件路径
log_file="system_monitor.log"

# 函数：获取 CPU 使用率
get_cpu_usage() {
    top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}'
}

# 函数：获取内存使用率
get_memory_usage() {
    free | grep Mem | awk '{printf "%.2f", ($3 / $2) * 100}'
}
# 函数：获取磁盘 I/O 情况（这里简单获取读写速率）
get_disk_io() {
    iostat -dkx 1 2 | tail -n 1 | awk '{print $3 " " $4}'
}

# 无限循环，每隔 5 秒监控一次
while true; do
    cpu_usage=$(get_cpu_usage)
    memory_usage=$(get_memory_usage)
    disk_io=$(get_disk_io)

    # 获取当前时间
    current_time=$(date +"%Y-%m-%d %H:%M:%S")

    # 记录监控信息到日志文件
    echo "$current_time - CPU Usage: $cpu_usage%, Memory Usage: $memory_usage%, Disk I/O (Read/Write KBps): $disk_io" >> $log_file

    # 输出到控制台，方便查看
    echo "$current_time - CPU Usage: $cpu_usage%, Memory Usage: $memory_usage%, Disk I/O (Read/Write KBps): $disk_io"

    # 等待 5 秒
    sleep 5
done